﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Text.RegularExpressions;
using com.dz.ht.common;
using com.dz.ht.db;

namespace com.dz.ht.components
{
    public class BaiDuICONManager
    {
        /// <summary>
        /// 触发发送消息的事件
        /// </summary>
        public event SendMsgEventHandler SendMsg;
        /// <summary>
        /// 百度首页编码
        /// </summary>
        Encoding m_encoding = Encoding.GetEncoding("gb2312");

        private string m_soso_url = "http://www.baidu.com/s?wd={0}";

        DataManger m_data_manager = new DataManger();

        private int m_book_id;
        public int StartBookId
        {
            get { return m_book_id; }
            set { m_book_id = value; }
        }

        private bool m_is_icon = false;
        public bool IsICON
        {
            get { return m_is_icon; }
            set { m_is_icon = value; }
        }


        /// <summary>
        /// 发送消息到客户端
        /// </summary>
        /// <param name="i_msg"></param>
        private void SendMsg2Client(string i_msg)
        {
            SendMsgEventArgs e = new SendMsgEventArgs();
            e.Msg = i_msg;

            if (SendMsg != null)
            {
                SendMsg(this, e);
            }
        }

        /// <summary>
        /// 收集封面
        /// </summary>
        public void StartImageFromQD()
        {
            SendMsg2Client("开始收集封面...");

            string t_str_sql = "select bookId,chapterUrl,bookName from tbbook ";

            try
            {
                DataSet ds = m_data_manager.QueryData(t_str_sql);

                long t_book_id = 0;

                string t_site_book_id = string.Empty;



                if (ds != null && ds.Tables[0].Rows.Count > 0)
                {
                    for (int index = 0; index < ds.Tables[0].Rows.Count; index++)
                    {
                        if (!long.TryParse(ds.Tables[0].Rows[index]["bookId"].ToString(), out t_book_id))
                            t_book_id = 0;

                        Match t_mc = Regex.Match(ds.Tables[0].Rows[index]["chapterUrl"].ToString(), "\\d+", RegexOptions.IgnoreCase | RegexOptions.Compiled);

                        if (t_mc != null && t_mc.Groups.Count > 0)
                        {
                            t_site_book_id = t_mc.Groups[0].Value.ToString();
                        }

                        int t_ret = NetSiteCatchManager.DownLoadImage(string.Format("http://image.cmfu.com/books/{0}/{0}.jpg", t_site_book_id), t_book_id);
                        if (t_ret == Consts.Success)
                        {
                            SendMsg2Client(string.Format("成功下载：{0}封面", ds.Tables[0].Rows[index]["bookName"]));
                            BookDao t_book_dao = new BookDao();
                            t_book_dao.UpdateBookExistImage(t_book_id, 1);

                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error("获取封面失败" + ex.ToString());
            }
        }

        /// <summary>
        /// 获取评论
        /// </summary>
        public void StartReviewFromQD()
        {
            SendMsg2Client("开始收集评论");
            string t_str_sql = "select bookId,chapterUrl from tbbook a where not exists(select 1 from tbreview b where a.bookid=b.bookid)  order by a.click desc";

            try
            {
                DataSet ds = m_data_manager.QueryData(t_str_sql);

                long t_book_id = 0;

                string t_site_book_id = string.Empty;

                string t_html=string.Empty;

                if (ds != null && ds.Tables[0].Rows.Count > 0)
                {
                    for (int index = 0; index < ds.Tables[0].Rows.Count; index++)
                    {
                        if (!long.TryParse(ds.Tables[0].Rows[index]["bookId"].ToString(), out t_book_id))
                            t_book_id = 0;

                        Match t_mc = Regex.Match(ds.Tables[0].Rows[index]["chapterUrl"].ToString(), "\\d+", RegexOptions.IgnoreCase | RegexOptions.Compiled);

                        if (t_mc != null && t_mc.Groups.Count > 0)
                        {
                            t_site_book_id = t_mc.Groups[0].Value.ToString();
                        }

                        t_html = NetSiteCatchManager.ReadUrl(string.Format("http://c.pingba.qidian.com/BookComment.aspx?BookId={0}", t_site_book_id), Encoding.GetEncoding("gb2312"));

                        if (!string.IsNullOrEmpty(t_html))
                        {
                           MatchCollection t_ma = Regex.Matches(t_html, "<div[^<>]*?class=[\'\"]title[\'\"]?>.*?</div>\\s*?<div[^<>]*?class=[\'\"]?cont[\'\"]?\\s*?>(.*?)</div>", RegexOptions.IgnoreCase | RegexOptions.Compiled);

                           if (t_ma != null && t_ma.Count > 0)
                           {
                               foreach (Match t_mc_review in t_ma)
                               {
                                   string t_content = t_mc_review.Groups[1].Value.ToString();
                                   t_content = Regex.Replace(t_content, "<.*?>.*?<.*?>", "", RegexOptions.IgnoreCase | RegexOptions.Compiled);
                                   t_content = Regex.Replace(t_content, "<.*?>", "", RegexOptions.IgnoreCase | RegexOptions.Compiled);
                                   t_content=Regex.Replace(t_content,"\\d+起点币","",RegexOptions.IgnoreCase|RegexOptions.Compiled);
                                   t_content = Regex.Replace(t_content,"起点中文网", "", RegexOptions.IgnoreCase | RegexOptions.Compiled);
                                   t_content = Regex.Replace(t_content, "[a-zA-Z0-9]", "", RegexOptions.IgnoreCase | RegexOptions.Compiled);
                                   if (string.IsNullOrEmpty(t_content) || t_content.Length < 10)
                                       continue;
                                   SendMsg2Client(string.Format("获得评论：{0}", t_content));
                                   m_data_manager.InsertBookReview(t_book_id, t_content);
                               }
                           }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error("获取评论失败" + ex.ToString());
            }
        }

        public void StartCollect()
        {
            string t_html = string.Empty;
            long t_my_book_id = 0;

            try
            {
                DataSet ds = null;
                if (m_is_icon)
                {
                    ds = m_data_manager.GetBookICON();
                }
                else
                {
                    ds = m_data_manager.GetBookByReview(StartBookId);
                }


                string t_url = string.Empty;

                if (ds != null && ds.Tables[0].Rows.Count > 0)
                {
                    for (int index = 0; index < ds.Tables[0].Rows.Count; index++)
                    {
                        t_url = string.Format(m_soso_url,string.Format("{0} book 起点", ds.Tables[0].Rows[index]["bookName"]));

                        if (!long.TryParse(ds.Tables[0].Rows[index]["bookId"].ToString(), out t_my_book_id))
                            t_my_book_id = 0;

                        t_html = NetSiteCatchManager.ReadUrl(t_url, m_encoding);

                        if (!string.IsNullOrEmpty(t_html))
                        {
                           Match t_mc=Regex.Match(t_html,"<a[^<>]*?hrefs*=s*[\'\"]*([^\"\']*qidian.*?\\/(\\d+))[\'\"]*[^<>]*?>",RegexOptions.IgnoreCase|RegexOptions.Compiled);

                           if (t_mc != null)
                           {
                               if (IsICON)
                               {
                                   int t_ret = NetSiteCatchManager.DownLoadImage(string.Format("http://image.cmfu.com/books/{0}/{0}.jpg", t_mc.Groups[2].Value.ToString()), t_my_book_id);
                                   if (t_ret == Consts.Success)
                                   {
                                       SendMsg2Client(string.Format("成功下载：{0}封面", ds.Tables[0].Rows[index]["bookName"]));
                                       BookDao t_book_dao = new BookDao();
                                       t_book_dao.UpdateBookExistImage(t_my_book_id, 1);

                                   }
                                   continue;
                               }

                               t_html = NetSiteCatchManager.ReadUrl(string.Format("http://c.pingba.qidian.com/BookComment.aspx?BookId={0}", t_mc.Groups[2].Value.ToString()), Encoding.GetEncoding("gb2312"));

                               if (!string.IsNullOrEmpty(t_html))
                               {
                                   MatchCollection t_ma = Regex.Matches(t_html, "<div[^<>]*?class=[\'\"]title[\'\"]?>.*?</div>\\s*?<div[^<>]*?class=[\'\"]?cont[\'\"]?\\s*?>(.*?)</div>", RegexOptions.IgnoreCase | RegexOptions.Compiled);

                                   if (t_ma != null && t_ma.Count > 0)
                                   {
                                       foreach (Match t_mc_review in t_ma)
                                       {
                                           string t_content = t_mc_review.Groups[1].Value.ToString();
                                           t_content = Regex.Replace(t_content, "<.*?>.*?<.*?>", "", RegexOptions.IgnoreCase | RegexOptions.Compiled);
                                           t_content = Regex.Replace(t_content, "<.*?>", "", RegexOptions.IgnoreCase | RegexOptions.Compiled);
                                           t_content=Regex.Replace(t_content,"\\d+起点币","",RegexOptions.IgnoreCase|RegexOptions.Compiled);
                                           if (string.IsNullOrEmpty(t_content) || t_content.Length < 5)
                                               continue;
                                           SendMsg2Client(string.Format("获得评论：{0}", t_content));
                                           m_data_manager.InsertBookReview(t_my_book_id, t_content);
                                       }
                                   }
                               }
                           }
                           else
                           {
                               SendMsg2Client(string.Format("百度不存在：{0}封面", ds.Tables[0].Rows[index]["bookName"]));
                           }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error("获取百度封面及评论失败" + ex.ToString());
            }
        }

    }
}
